﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Security.Cryptography;

using PlugNT.Safe;
using PlugNT.Common;
using PlugNT.Database.Common;
using PlugNT.Database.Common.Simple;
using PlugNT.Custom;
using PlugNT.Cms.Model;

namespace PlugNT.Cms.DAL
{
    public class SysModel
    {
        //先计算好每个模型的文章数-放入内存-在内存中计算
        internal static string currTableName = WebConfig.TablePrefix + "sys_model";

        internal static Dictionary<int, SysModelInfo> models = null;
        private static List<int> indexs = null;


        static SysModel()
        {
            models = new Dictionary<int, SysModelInfo>();
            indexs = new List<int>();
            
            IDataReader dr = GetReader(-1, "*", "");
            
            if (dr != null)
            {
                while(dr.Read())
                {
                    int type = int.Parse(dr["type"].ToString());
                    SysModelInfo model = CreateSysModelInfo(type);
                    model.id = int.Parse(dr["id"].ToString());
                    model.name = dr["name"].ToString();
                    model.type = type;
                    model.enable = dr["enable"].ToString() == "1";
                    model.is_fixed = dr["is_fixed"].ToString() == "1";
                    model.channel_no_list = dr["channel_no_list"].ToString();

                    model.msg_locked = dr["msg_locked"].ToString() == "1";
                    model.image_locked = dr["image_locked"].ToString() == "1";
                    model.msg_style = int.Parse(dr["msg_style"].ToString());
                    model.visit_max_count = int.Parse(dr["visit_max_count"].ToString());
                    model.visit_max_time = DateTime.Parse(dr["visit_max_time"].ToString());

                    model.arr_str = dr["arr_str"].ToString();
                    model.ArrBind();

                    models.Add(model.id, model);
                    indexs.Add(model.id);
                }
                dr.Close();
            }
        }


        #region 获取一个实体

        public static int GetDictionaryCount()
        {
            return indexs.Count;
        }

        public static SysModelInfo GetSysModelInfoByIndex(int index)
        {
            SysModelInfo info = null;
            models.TryGetValue(indexs[index], out info);
            return info;
        }

        public static bool Exists(int id)
        {
            return models.ContainsKey(id);
        }

        public static SysModelInfo GetSysModelInfoFromDictionary(int id)
        {
            //default(value);
            SysModelInfo info=null;
            models.TryGetValue(id, out info);
            return info;
        }

        public static SysModelInfo CreateSysModelInfo(int type)
        {
            SysModelInfo model = null;
            switch (type)
            {
                case SysModelType.Info:
                    model = new InfoModelInfo();
                    break;
                case SysModelType.Shop:
                    model = new ShopModelInfo();
                    break;
                case SysModelType.Bbs:
                    model = new BbsModelInfo();
                    break;
                default:
                    model = new InfoModelInfo();
                    break;
            }
            return model;
        }

        #endregion

        #region 添加，修改，删除操作

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool Add(SysModelInfo model)
        {

            StringBuilder strSql = new StringBuilder();
            strSql.Append("insert into " + currTableName + "(");
            strSql.Append("[id],[name],[type],[enable],is_fixed,channel_no_list,msg_locked,image_locked,msg_style,visit_max_count,visit_max_time,arr_str");
            strSql.Append(")");
            strSql.Append(" values (");
            strSql.Append(model.id.ToString() + ",");
            strSql.Append("'" + PlugNT.Safe.StringHelper.SqlFilter(model.name) + "',");
            strSql.Append(model.type.ToString() + ",");
            strSql.Append((model.enable ? "1" : "0") + ",");
            strSql.Append((model.is_fixed ? "1" : "0") + ",");
            strSql.Append("'" + PlugNT.Safe.StringHelper.SqlFilter(model.channel_no_list) + "',");

            strSql.Append((model.msg_locked ? "1" : "0") + ",");
            strSql.Append((model.image_locked ? "1" : "0") + ",");
            strSql.Append( model.msg_style.ToString() + ",");
            strSql.Append( model.visit_max_count.ToString() + ",");
            strSql.Append("'" + model.visit_max_time.ToString() + "',");
            strSql.Append("'" + PlugNT.Safe.StringHelper.SqlFilter(model.arr_str) + "'");

            strSql.Append(")");

            if (DbHelper.ExecuteSql(strSql.ToString()) > 0)
            {
                models.Add(model.id, model);
                indexs.Add(model.id);
                return true;
            }
            else
            {
                return false;
            }

        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool Update(SysModelInfo model)
        {
            StringBuilder strSql = new StringBuilder();

            strSql.Append("update " + currTableName + " set ");
            strSql.Append("[name]='" + PlugNT.Safe.StringHelper.SqlFilter(model.name) + "',");
            //strSql.Append("[type]=" + model.type.ToString() + ",");
            strSql.Append("[enable]=" + (model.enable ? "1" : "0") + ",");
            //strSql.Append("is_fixed=" + (model.is_fixed ? "1" : "0"));
            strSql.Append("channel_no_list='" + PlugNT.Safe.StringHelper.SqlFilter(model.channel_no_list) + "',");
            strSql.Append("[msg_locked]=" + (model.msg_locked ? "1" : "0") + ",");
            strSql.Append("[image_locked]=" + (model.image_locked ? "1" : "0") + ",");
            strSql.Append("[msg_style]=" + model.msg_style.ToString() + ",");
            strSql.Append("[visit_max_count]=" + model.visit_max_count.ToString() + ",");
            strSql.Append("[visit_max_time]='" + model.visit_max_time.ToString() + "'");
            if (model.arr_str != "")
            {
                strSql.Append(",[arr_str]='" +  PlugNT.Safe.StringHelper.SqlFilter(model.arr_str) + "'");
            }
            strSql.Append(" where [id]=" + model.id.ToString());

            if (DbHelper.ExecuteSql(strSql.ToString()) > 0)
            {
                models[model.id]= model;
                return true;
            }
            else
            {
                return false;
            }
        }

        public bool UpdateVisitMax(int id, int visitMaxCount, DateTime visitMaxTime)
        {
            StringBuilder strSql = new StringBuilder();

            strSql.Append("update " + currTableName + " set ");
            strSql.Append("[visit_max_count]=" + visitMaxCount.ToString() + ",");
            strSql.Append("[visit_max_time]='" + visitMaxTime.ToString() + "'");

            strSql.Append(" where [id]=" + id.ToString());

            if (DbHelper.ExecuteSql(strSql.ToString()) > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        //public bool UpdateArr(int id, string strArr)
        //{
        //    StringBuilder strSql = new StringBuilder();

        //    strSql.Append("update " + currTableName + " set ");
        //    strSql.Append("[arr_str]='" + strArr + "'");

        //    strSql.Append(" where [id]=" + id.ToString());

        //    if (DbHelper.ExecuteSql(strSql.ToString()) > 0)
        //    {
        //        return true;
        //    }
        //    else
        //    {
        //        return false;
        //    }
        //}

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Delete(int id)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from " + currTableName);
            strSql.Append(" where id=" + id.ToString());

            if (DbHelper.ExecuteSql(strSql.ToString()) > 0)
            {
                models.Remove(id);
                indexs.Remove(id);
                return true;
            }
            else
            {
                return false;
            }
        }

        #endregion

        #region 获取数据

        /// <summary>
        /// 得到IDataReader
        /// </summary>
        /// <param name="topCount">-1表示全部</param>
        /// <param name="colNames"></param>
        /// <param name="andWhere"></param>
        /// <returns></returns>
        private static IDataReader GetReader(int topCount, string colNames, string andWhere)
        {
            string sql = "select " + (topCount == -1 ? "" : "top " + topCount) + " " + colNames + " from " + currTableName + " where 1=1 " + andWhere;
            return DbHelper.ExecuteReader(sql);
        }


        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="andWhere"></param>
        /// <returns></returns>
        public static DataTable GetList(string andWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select a.*,b.title from  [" + currTableName + "] as a left join " + Channel.currTableName + " as b on a.channel_no_list=b.no_list where 1=1 ");
            strSql.Append((" " + andWhere).Replace(" and ", " and a."));
            return DbHelper.GetDataTable(strSql.ToString());
        }



        #endregion





    }
}
